package cn.jack.okhttpdemo;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.util.Log;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.retrofit2.converter.GsonConverterFactory;
import com.squareup.retrofit2.retrofit.Retrofit;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import cn.jack.okhttp.okhttp3.Cache;
import cn.jack.okhttp.okhttp3.Call;
import cn.jack.okhttp.okhttp3.Callback;
import cn.jack.okhttp.okhttp3.OkHttpClient;
import cn.jack.okhttp.okhttp3.Request;
import cn.jack.okhttp.okhttp3.Response;
import cn.jack.okhttpdemo.api.ApiService;
import cn.jack.okhttpdemo.bean.UserInfo;
import cn.jack.okhttpdemo.interceptor.MyCacheInterceptor;
import cn.jack.okhttpdemo.util.UnicodeUtil;
import cn.jack.okio.BufferedSink;
import cn.jack.okio.BufferedSource;
import cn.jack.okio.Okio;
import cn.jack.okio.Source;

public class MainActivity extends FragmentActivity {

    private TextView tvRequest;
    private TextView tvResult;
    private Cache cache;
    private OkHttpClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        File externalCacheDir = getExternalCacheDir();
        File file = new File(externalCacheDir.getAbsolutePath(), "temp.txt");
        BufferedSink buffer = null;
        try {
            buffer = Okio.buffer(Okio.sink(file));
            buffer.writeUtf8("能花啥打法上\n");
            buffer.writeUtf8("能花啥打法上\n");
            buffer.writeUtf8("能花啥打法上\n");
            buffer.writeUtf8("能花啥打法上");
            buffer.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            Source source = Okio.source(file);
            BufferedSource bufferedSource = Okio.buffer(source);
            while (!bufferedSource.exhausted()) {
                String readUtf8Line = bufferedSource.readUtf8Line();
                Log.e("jiang", "onCreate: " + readUtf8Line);

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            Log.e("jiang", "onCreate: " + e.toString());
            e.printStackTrace();
        }

        setContentView(R.layout.activity_main);
        tvRequest = findViewById(R.id.am_tv_request);
        tvResult = findViewById(R.id.am_tv_result);
        tvRequest.setOnClickListener(v -> {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    client = new OkHttpClient.Builder()
                            .addInterceptor(new MyCacheInterceptor())
                            .cache(cache)
//                            .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("qq.com", 443)))
//                            .proxySelector(new ProxySelector() {
//                                @Override
//                                public List<Proxy> select(URI uri) {
//                                    return Collections.singletonList(Proxy.NO_PROXY);
//                                }
//
//                                @Override
//                                public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
//
//                                }
//                            })
                            .build();
                    requestData();
                }
            }).start();
//            requestRetrofitData();
        });

        //缓存文件夹
        File cacheFile = new File(Objects.requireNonNull(getExternalCacheDir()).toString(), "demoCache");
        //缓存大小为10M
        int cacheSize = 10 * 1024 * 1024;
        //创建缓存对象
        cache = new Cache(cacheFile, cacheSize);


    }

    private void requestRetrofitData() {
        Retrofit retrofit = new Retrofit.Builder()
                .client(new OkHttpClient())
                .baseUrl("https://api.lhhd.ltd/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ApiService service = retrofit.create(ApiService.class);

        service.getUserInfo().enqueue(new com.squareup.retrofit2.retrofit.Callback<UserInfo>() {
            @Override
            public void onResponse(com.squareup.retrofit2.retrofit.Call<UserInfo> call, com.squareup.retrofit2.retrofit.Response<UserInfo> response) {

                tvResult.setText(new Gson().toJson(response.body()));
            }

            @Override
            public void onFailure(com.squareup.retrofit2.retrofit.Call<UserInfo> call, Throwable t) {
                tvResult.setText(t.getMessage());
            }
        });
    }

    private void requestData() {

        Request request = new Request.Builder()
                .url("https://qq.com/")
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    tvResult.setText(e.getMessage());
                });
            }

            @Override
            public void onResponse(Call call, Response response) {
                String string = null;
                try {
                    string = response.body().string();
                    String finalString = string;
                    runOnUiThread(() -> {
                        tvResult.setText(Html.fromHtml(UnicodeUtil.decodeUnicode(finalString)));
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }
}
